package gtgold;

import java.awt.*;
import java.awt.event.*;
import java.util.Map;

import javax.swing.*;

/**
 * aka G.O.D. (lol)
 * 
 * @author jo
 */
public class GenericOptionDialog extends JDialog
{
	private static final long serialVersionUID = 1L;
	private Object returnValue;

	public GenericOptionDialog(String text,
			Map<? extends Object, String> options, boolean allowCancel)
	{
		super(OregonTrail.frame, "Option", true);

		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		setResizable(false);
		setPreferredSize(new Dimension(300, 150 + options.size() * 75));
		setLayout(new GridLayout(allowCancel ? 3 + options.size()
				: 1 + options.size(), 1));

		// wrap in JPanel to center text
		final String _text = text;
		add(new JPanel()
		{
			private static final long serialVersionUID = 1L;

			{ // R1
				add(new JLabel(_text));
			}
		});

		// R2-RN
		for (Map.Entry<? extends Object, String> e : options.entrySet())
		{
			JButton butt = new JButton(e.getValue());
			butt.addActionListener(new ButtonListener(e.getKey()));
			add(butt);
		}

		if (allowCancel)
		{
			add(new JPanel()); // spacing gap R(N+1)

			JButton cancel = new JButton("Cancel");
			cancel.addActionListener(new ActionListener()
			{
				public void actionPerformed(ActionEvent e)
				{
					dispose();
				}
			});
			add(cancel); // R(N+2)
		}

		// JDialog initialization
		pack();
		setLocationRelativeTo(OregonTrail.frame);
	}

	public Object showDialog()
	{
		setVisible(true); // modal dialog freezes here until user in
		return returnValue;
	}

	private class ButtonListener implements ActionListener
	{
		private Object _returnValue;

		public ButtonListener(Object returnValue)
		{
			_returnValue = returnValue;
		}

		@Override
		public void actionPerformed(ActionEvent e)
		{
			returnValue = _returnValue;
			dispose();
		}

	}

}
